package com.bbf.springmvcdemo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 加载/读取配置文件，在service-config.xml中配置
 * @author BBF
 */
public class WebPropertyHolder extends PropertyPlaceholderConfigurer {
  private static final Logger LOGGER = LoggerFactory.getLogger(WebPropertyHolder.class);
  private static Map<String, String> ctxPropertiesMap;

  @Override
  protected synchronized void processProperties(
      ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) {
    super.processProperties(beanFactoryToProcess, props);
    Set<Object> propArr;
    try {
      propArr = props.keySet();
      int len = propArr.size();
      if (0 < len) {
        ctxPropertiesMap = new ConcurrentHashMap<>(len);
        //迭代遍历set集合
        Iterator<Object> iterator = propArr.iterator();
        while (iterator.hasNext()) {
          Object one = iterator.next();
          String keyStr = one.toString();
          ctxPropertiesMap.put(keyStr, props.getProperty(keyStr));
        }
      }
    } catch (Exception e) {
      LOGGER.error("[WebPropertyHolder.processProperties]", e);
    }
  }

  /**
   * 获取配置项的内容
   * @param key 配置项名称
   * @return 配置项内容，若无此配置项，则返回null
   */
  public static String getContextProperty(String key) {
    if (null != ctxPropertiesMap) {
      return ctxPropertiesMap.get(key);
    }
    return null;
  }
}